package org.bhujmandir.android;

import org.bhujmandir.android.utils.DBController;
import org.bhujmandir.android.utils.MyApplication;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MediaActivity extends Activity{
	Context context;
	ListView itemsListView;
	TextView title;
	DBController dbController;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.main);
		dbController = new DBController();
		Bundle extraVars = this.getIntent().getExtras();
		title = (TextView)findViewById(R.id.title);
		String titleString = extraVars.getString("title");
		title.setText(titleString);
		itemsListView = (ListView)findViewById(R.id.listView);
		
	    String mediaType = extraVars.getString("type");
	    Boolean sort = extraVars.getBoolean("sort");
	    
	    Cursor mediaCursor = dbController.fetchMedia(mediaType, null, null, null,sort);
	    startManagingCursor(mediaCursor);
	    myCursorAdapter mediaAdapter = new myCursorAdapter(context,mediaCursor);
	    itemsListView.setAdapter(mediaAdapter);
		
	    /*
	    itemsListView.setOnItemClickListener(new OnItemClickListener() {
	   		public void onItemClick(AdapterView<?> parent, View view,
	   			int position, long id) {
	       // When clicked, show a toast with the TextView text
	   			Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
	   					Toast.LENGTH_SHORT).show();
	   		}
	   	});*/
	    
	}
	
	public class myCursorAdapter extends CursorAdapter{
		LayoutInflater inflater;
		public myCursorAdapter(Context context, Cursor cursor) {
			super(context, cursor);
			inflater = LayoutInflater.from(context);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView nameField = (TextView)view.findViewById(R.id.mediaName);
			nameField.setText(cursor.getString(cursor.getColumnIndex("title")));
			
			TextView albumField = (TextView)view.findViewById(R.id.albumName);
			albumField.setText(cursor.getString(cursor.getColumnIndex("album")));
			
			TextView artistField = (TextView)view.findViewById(R.id.artistName);
			artistField.setText(cursor.getString(cursor.getColumnIndex("artist")));
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			Log.v(MyApplication.TAG,"newView");
			View v = inflater.inflate(R.layout.media_view, parent,false);
			return v;
		}
	}
}
